package com.woniu.humanresource.service.impl;

import com.woniu.humanresource.entity.JWTUtil;
import com.woniu.humanresource.entity.User;
import com.woniu.humanresource.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    //自动注入认证对象管理器
    @Autowired
    AuthenticationManager authenticationManager;

    //判断是否合法合法就生成token并返回
    @Override
    public String login(User user) {
        //第一件事把user对象转换成Authentication认证对象
        Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUname(), user.getPassword());
        //调用认证管理器的 认证authentication对象
        authenticationManager.authenticate(authentication);
        //底层authentication会和UserDetail对此
        //不匹配会自动抛异常
        //账号密码匹配 就生成token返回
        String token = JWTUtil.create(user.getUname());
        //System.out.println(token);
        return token;
    }
}
